<?php
namespace app\wechat\controller;
use think\Controller;
use think\Request;
use think\Hook;
use Wechat\TPWechat;

class WechatOauth extends Controller
{
    protected $_action;
    protected $_controller;
    protected $wechatObj;
    protected $scope;

    // 发起微信授权
    function index() {
        //dump($_SERVER);
        session('base_url', $_SERVER['HTTP_REFERER']);
        $scope = input('param.scope', 'snsapi_userinfo');
        $this->scope = $scope;
        //dump(session(''));
        $this->oauth(); // 发起授权
    }

    protected function getWechtObj() {
        if ($this->wechatObj == null) {
            $options = config('wechat');
            $this->wechatObj = new TPWechat($options);
        }
        return $this->wechatObj;
    }

    function is_weixin() {
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }

    //微信回调页面
    public function baseweixinlogin() {
        $code = isset($_GET['code']) ? $_GET['code'] : '';
        if (!$code)
            $this->error('错误页面1');

        $oauthAccessToken = $this->getWechtObj()->getOauthAccessToken();
        //dump($oauthAccessToken);

        if (!$oauthAccessToken)
            $this->error('获取授权失败');

        $userInfo = $this->getWechtObj()->getUserinfo($oauthAccessToken['openid']);
        //dump($userInfo);exit;
        if (isset($userInfo['subscribe']) && $userInfo['subscribe'] == 0) {
            $this->redirect(url('base/subscribe'));
        }
        if (!$userInfo){
            unlink('./access_token.json'); // 删除access_token 文件
            //跳转重新发起授权请求
            $this->oauth();
        }

        $url = session('base_url') . '?' . http_build_query($userInfo);
        exit('<script>window.location.href="'.$url.'"</script>');
    }

    public function oauth() {
        $url = request()->domain() . url('wechat/Wechat_oauth/baseweixinlogin');
        $url = $this->getWechtObj()->getOauthRedirect($url, '', $this->scope);
        exit('<script>window.location.href="'.$url.'"</script>');
    }
}
